package dk.eal.kbr.mule.component.exchange;

import java.text.SimpleDateFormat;
import java.util.Date;

import microsoft.exchange.webservices.data.Appointment;
import microsoft.exchange.webservices.data.ExchangeService;
import microsoft.exchange.webservices.data.MessageBody;
import microsoft.exchange.webservices.data.SendInvitationsMode;

public class CreateCalenderItem extends ExchangeProxy {

	@Override
	public ExchangeCalenderItem doWork(ExchangeCalenderItem calenderItem)
			throws Exception {

		try {
			Appointment appointment = createAppointment(calenderItem);
			calenderItem.setExchangeItemId(appointment.getId().getUniqueId());
			calenderItem.setIsActive(1);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace(); // Test kode
			throw new Exception(e);
		}

		return calenderItem;
	}

	public Appointment createAppointment(ExchangeCalenderItem externalData)
			throws Exception {

		Appointment appointment;

		ExchangeService service = connect(externalData.email,
				externalData.password);

		appointment = new Appointment(service);

		appointment.setSubject(externalData.getSubject());
		appointment.setBody(MessageBody
				.getMessageBodyFromText(externalData.getBody()));


		Date startDate = externalData.getStartTimestamp(); // formatter.parse("2012-06-19 12:00:00");
		Date endDate = externalData.getEndTimestamp();// formatter.parse("2012-06-19 13:00:00");
		appointment.setStart(startDate);// new Date(2010-1900,5-1,20,20,00));
		appointment.setEnd(endDate); // new Date(2010-1900,5-1,20,21,00));
		appointment.getRequiredAttendees().clear();

		appointment.save(SendInvitationsMode.SendToNone);

		return appointment;
	}

}
